import axios from 'axios'
import router from "@/router";
import config from "@/config/config.js";

const request = axios.create({
    baseURL: config.baseUrl,
    timeout: 20000,
})

// 请求拦截器
request.interceptors.request.use(config => {
        config.data = JSON.stringify(config.data)
        config.headers = {
            'Content-Type': 'application/json'
        }
        let token = localStorage.getItem('token')
        if (token) {
            config.headers.token = token
            config.headers.state = token
        } else {
            router.push({
                path: '/login'
            })
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code !== 200) {
            return Promise.reject(res.message)
        }
        return res.data
    },
    error => {
        error.message = error.response.data.msg
        if ("State不存在或已过期" === error.response.data.msg) {
            localStorage.removeItem("token");
            router.push({
                path: '/login'
            })
        }
        return Promise.reject(error)
    }
)

export default request
